<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/home" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center cart-badge">{{ cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">设置</h1>
        <p class="text-gray-600">管理您的账户设置和偏好</p>
      </div>

      <!-- 设置内容 -->
      <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <!-- 左侧菜单 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <nav class="space-y-2">
              <button
                v-for="item in settingsMenu"
                :key="item.key"
                @click="activeTab = item.key"
                :class="[
                  'w-full text-left px-4 py-3 rounded-lg transition-colors flex items-center',
                  activeTab === item.key 
                    ? 'bg-primary/10 text-primary font-medium' 
                    : 'text-gray-600 hover:bg-gray-50 hover:text-gray-800'
                ]"
              >
                <i :class="item.icon" class="mr-3 text-lg"></i>
                {{ item.label }}
              </button>
            </nav>
          </div>
        </div>

        <!-- 右侧内容 -->
        <div class="lg:col-span-3">
          <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <!-- 个人信息设置 -->
            <div v-if="activeTab === 'profile'" class="space-y-6">
              <h2 class="text-xl font-semibold text-gray-800 mb-4">个人信息</h2>
              
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                  <el-input v-model="userInfo.username" placeholder="请输入用户名" />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
                  <el-input v-model="userInfo.email" placeholder="请输入邮箱" />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
                  <el-input v-model="userInfo.phone" placeholder="请输入手机号" />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">真实姓名</label>
                  <el-input v-model="userInfo.realName" placeholder="请输入真实姓名" />
                </div>
              </div>

              <div class="flex justify-end">
                <el-button type="primary" @click="saveProfile">保存更改</el-button>
              </div>
            </div>

            <!-- 安全设置 -->
            <div v-if="activeTab === 'security'" class="space-y-6">
              <h2 class="text-xl font-semibold text-gray-800 mb-4">安全设置</h2>
              
              <div class="space-y-4">
                <div class="border border-gray-200 rounded-lg p-4">
                  <div class="flex items-center justify-between">
                    <div>
                      <h3 class="font-medium text-gray-800">修改密码</h3>
                      <p class="text-sm text-gray-600">定期更换密码以保护账户安全</p>
                    </div>
                    <el-button @click="showChangePassword = true">修改</el-button>
                  </div>
                </div>

                <div class="border border-gray-200 rounded-lg p-4">
                  <div class="flex items-center justify-between">
                    <div>
                      <h3 class="font-medium text-gray-800">两步验证</h3>
                      <p class="text-sm text-gray-600">为您的账户添加额外的安全保护</p>
                    </div>
                    <el-switch v-model="securitySettings.twoFactorAuth" />
                  </div>
                </div>

                <div class="border border-gray-200 rounded-lg p-4">
                  <div class="flex items-center justify-between">
                    <div>
                      <h3 class="font-medium text-gray-800">登录通知</h3>
                      <p class="text-sm text-gray-600">新设备登录时发送邮件通知</p>
                    </div>
                    <el-switch v-model="securitySettings.loginNotification" />
                  </div>
                </div>
              </div>
            </div>

            <!-- 帮助与反馈 -->
            <div v-if="activeTab === 'help'" class="space-y-6">
              <h2 class="text-xl font-semibold text-gray-800 mb-4">帮助与反馈</h2>

              <!-- 常见问题 -->
              <div class="mb-8">
                <h3 class="text-lg font-medium text-gray-800 mb-4">常见问题</h3>
                <div class="space-y-3">
                  <div class="border border-gray-200 rounded-lg">
                    <button
                      @click="toggleFaq(0)"
                      class="w-full text-left p-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
                    >
                      <span class="font-medium text-gray-800">如何修改个人信息？</span>
                      <i :class="['fas', 'fa-chevron-down', 'text-gray-400', 'transition-transform', { 'rotate-180': expandedFaq === 0 }]"></i>
                    </button>
                    <div v-show="expandedFaq === 0" class="px-4 pb-4 text-gray-600">
                      您可以在"个人信息"页面中修改您的用户名、邮箱、手机号等信息，修改后点击"保存更改"即可。
                    </div>
                  </div>

                  <div class="border border-gray-200 rounded-lg">
                    <button
                      @click="toggleFaq(1)"
                      class="w-full text-left p-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
                    >
                      <span class="font-medium text-gray-800">如何修改密码？</span>
                      <i :class="['fas', 'fa-chevron-down', 'text-gray-400', 'transition-transform', { 'rotate-180': expandedFaq === 1 }]"></i>
                    </button>
                    <div v-show="expandedFaq === 1" class="px-4 pb-4 text-gray-600">
                      在"安全设置"页面中点击"修改密码"按钮，输入当前密码和新密码即可完成修改。
                    </div>
                  </div>

                  <div class="border border-gray-200 rounded-lg">
                    <button
                      @click="toggleFaq(2)"
                      class="w-full text-left p-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
                    >
                      <span class="font-medium text-gray-800">如何查看我的订单？</span>
                      <i :class="['fas', 'fa-chevron-down', 'text-gray-400', 'transition-transform', { 'rotate-180': expandedFaq === 2 }]"></i>
                    </button>
                    <div v-show="expandedFaq === 2" class="px-4 pb-4 text-gray-600">
                      点击右上角用户头像，选择"我的订单"即可查看所有订单信息和状态。
                    </div>
                  </div>

                  <div class="border border-gray-200 rounded-lg">
                    <button
                      @click="toggleFaq(3)"
                      class="w-full text-left p-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
                    >
                      <span class="font-medium text-gray-800">如何联系客服？</span>
                      <i :class="['fas', 'fa-chevron-down', 'text-gray-400', 'transition-transform', { 'rotate-180': expandedFaq === 3 }]"></i>
                    </button>
                    <div v-show="expandedFaq === 3" class="px-4 pb-4 text-gray-600">
                      您可以通过以下方式联系我们：<br>
                      • 客服热线：400-800-1234<br>
                      • 邮箱：service@bookstore.com<br>
                      • 在线客服：工作日 9:00-18:00
                    </div>
                  </div>
                </div>
              </div>

              <!-- 意见反馈 -->
              <div>
                <h3 class="text-lg font-medium text-gray-800 mb-4">意见反馈</h3>
                <div class="bg-gray-50 rounded-lg p-6">
                  <el-form :model="feedbackForm" label-width="80px" class="space-y-4">
                    <el-form-item label="反馈类型">
                      <el-select v-model="feedbackForm.type" placeholder="请选择反馈类型" style="width: 200px">
                        <el-option label="功能建议" value="suggestion" />
                        <el-option label="问题反馈" value="bug" />
                        <el-option label="服务投诉" value="complaint" />
                        <el-option label="其他" value="other" />
                      </el-select>
                    </el-form-item>

                    <el-form-item label="反馈标题">
                      <el-input
                        v-model="feedbackForm.title"
                        placeholder="请简要描述您的反馈"
                        maxlength="50"
                        show-word-limit
                      />
                    </el-form-item>

                    <el-form-item label="详细内容">
                      <el-input
                        v-model="feedbackForm.content"
                        type="textarea"
                        :rows="5"
                        placeholder="请详细描述您的问题或建议，我们会认真对待每一条反馈"
                        maxlength="500"
                        show-word-limit
                      />
                    </el-form-item>

                    <el-form-item label="联系方式">
                      <el-input
                        v-model="feedbackForm.contact"
                        placeholder="请留下您的邮箱或手机号，方便我们回复（可选）"
                        maxlength="50"
                      />
                    </el-form-item>

                    <el-form-item>
                      <div class="flex space-x-3">
                        <el-button type="primary" @click="submitFeedback">提交反馈</el-button>
                        <el-button @click="resetFeedback">重置</el-button>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </div>

              <!-- 联系信息 -->
              <div class="bg-blue-50 rounded-lg p-6">
                <h3 class="text-lg font-medium text-gray-800 mb-3 flex items-center">
                  <i class="fas fa-info-circle text-blue-500 mr-2"></i>
                  联系我们
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
                  <div class="flex items-center">
                    <i class="fas fa-phone text-blue-500 mr-2"></i>
                    客服热线：400-800-1234
                  </div>
                  <div class="flex items-center">
                    <i class="fas fa-envelope text-blue-500 mr-2"></i>
                    邮箱：service@bookstore.com
                  </div>
                  <div class="flex items-center">
                    <i class="fas fa-clock text-blue-500 mr-2"></i>
                    服务时间：周一至周日 9:00-22:00
                  </div>
                  <div class="flex items-center">
                    <i class="fas fa-map-marker-alt text-blue-500 mr-2"></i>
                    地址：北京市朝阳区建国路88号
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showChangePassword" title="修改密码" width="400px">
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="当前密码">
          <el-input v-model="passwordForm.currentPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showChangePassword = false">取消</el-button>
          <el-button type="primary" @click="changePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 回到顶部按钮 -->
    <BackToTop />
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage } from 'element-plus'
import BackToTop from '@/components/BackToTop.vue'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const activeTab = ref('profile')
const showChangePassword = ref(false)
const expandedFaq = ref(null)

// 计算购物车数量
const cartCount = computed(() => cartStore.cartCount)

// 设置菜单
const settingsMenu = reactive([
  { key: 'profile', label: '个人信息', icon: 'fas fa-user' },
  { key: 'security', label: '安全设置', icon: 'fas fa-shield-alt' },
  { key: 'help', label: '帮助与反馈', icon: 'fas fa-question-circle' }
])

// 用户信息
const userInfo = reactive({
  username: userStore.userInfo?.username || '',
  email: userStore.userInfo?.email || '',
  phone: userStore.userInfo?.phone || '',
  realName: userStore.userInfo?.realName || ''
})

// 安全设置
const securitySettings = reactive({
  twoFactorAuth: false,
  loginNotification: true
})

// 帮助与反馈
const feedbackForm = reactive({
  type: 'suggestion',
  title: '',
  content: '',
  contact: ''
})

// 修改密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const goToCart = () => {
  router.push('/cart')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      // 当前已在设置页面，不需要跳转
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 保存个人信息
const saveProfile = () => {
  // 这里应该调用API保存用户信息
  ElMessage.success('个人信息已保存')
}

// 修改密码
const changePassword = () => {
  if (!passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
    ElMessage.error('请填写完整的密码信息')
    return
  }

  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  if (passwordForm.newPassword.length < 6) {
    ElMessage.error('新密码长度不能少于6位')
    return
  }

  // 这里应该调用API修改密码
  ElMessage.success('密码修改成功')
  showChangePassword.value = false

  // 重置表单
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

// FAQ展开/收起
const toggleFaq = (index) => {
  expandedFaq.value = expandedFaq.value === index ? null : index
}

// 提交反馈
const submitFeedback = () => {
  if (!feedbackForm.title.trim()) {
    ElMessage.error('请填写反馈标题')
    return
  }

  if (!feedbackForm.content.trim()) {
    ElMessage.error('请填写详细内容')
    return
  }

  // 这里应该调用API提交反馈
  ElMessage.success('反馈提交成功，我们会尽快处理您的反馈')
  resetFeedback()
}

// 重置反馈表单
const resetFeedback = () => {
  feedbackForm.type = 'suggestion'
  feedbackForm.title = ''
  feedbackForm.content = ''
  feedbackForm.contact = ''
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}
</script>

<style scoped>
/* 自定义样式 */

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: #FF6B8B;
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: #FF6B8B;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #FF6B8B;
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.bg-primary\/10 {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

.hover\:bg-primary:hover {
  background-color: #FF6B8B !important;
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.cart-badge {
  z-index: 10;
  transform: translate(25%, -25%);
  min-width: 18px;
  height: 18px;
}

/* 设置页面特有样式 */
.settings-card {
  transition: all 0.3s ease;
}

.settings-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-button--primary) {
  background-color: #FF6B8B !important;
  border-color: #FF6B8B !important;
  color: white !important;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  background-color: #E55A7A !important;
  border-color: #E55A7A !important;
  color: white !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 138, 0.3);
}

:deep(.el-button--primary:focus) {
  background-color: #FF6B8B !important;
  border-color: #FF6B8B !important;
  color: white !important;
}

:deep(.el-button--primary:active) {
  background-color: #E55A7A !important;
  border-color: #E55A7A !important;
  color: white !important;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #FF6B8B !important;
  border-color: #FF6B8B !important;
}

:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  border-color: #FF6B8B !important;
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2) !important;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
}

:deep(.el-dialog__body) {
  padding: 10px 20px 20px;
}

:deep(.el-form-item__label) {
  color: #374151;
  font-weight: 500;
}

/* 确保按钮样式优先级 */
.el-button.el-button--primary {
  background-color: #FF6B8B !important;
  border-color: #FF6B8B !important;
  color: white !important;
}

.el-button.el-button--primary:hover {
  background-color: #E55A7A !important;
  border-color: #E55A7A !important;
  color: white !important;
}

.el-button.el-button--primary:focus {
  background-color: #FF6B8B !important;
  border-color: #FF6B8B !important;
  color: white !important;
}

.el-button.el-button--primary:active {
  background-color: #E55A7A !important;
  border-color: #E55A7A !important;
  color: white !important;
}
</style>
